<?php


namespace App\Web\Model;


use App\Service\FileHandler;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Log;
use EchoPHP\File\File;
use EchoPHP\File\UploadedFile;
use Ramsey\Uuid\Uuid;

class Attach extends Model {

    /**
     * 图片类型
     */
    const TYPE_IMG = 1;
    /**
     * 其他类型附件
     */
    const TYPE_OTHER = 9;

    /**
     * 简历附件
     */
    const MODULE_RESUME = 'resume';

    /**
     * 生成附件ID
     * @return string
     * @throws \Exception
     */
    public function generateAttachId() {
        return Uuid::uuid1()->toString();
    }

    /**
     * 文件上传处理
     * @param UploadedFile $file
     * @param $module
     * @param $oprId
     * @return array|bool
     * @throws \Exception
     */
    public function uploadAttach(UploadedFile $file, $module, $oprId, $attachName = null) {
        if (!$attachName) {
            $attachName = $file->getClientOriginalName();
        }
        return $this->fileHandle($file, $attachName, $module, $oprId);
    }

    /**
     * 附件文件移动
     * @param File $file
     * @param $module
     * @param $oprId
     * @param bool $keepOld
     * @return array|bool
     * @throws \Exception
     */
    public function moveAttach(File $file, $module, $oprId, $attachName = null, $keepOld = false) {
        if (!$attachName) {
            $attachName = $file->getFilename();
        }
        return $this->fileHandle($file, $attachName, $module, $oprId, $keepOld);
    }

    /**
     * 文件处理  移动到指定目录并写入数据库中
     * @param $file
     * @param $attachName
     * @param $module
     * @param $oprId
     * @param bool $keepOld
     * @return array|bool
     * @throws \Exception
     */
    protected function fileHandle($file, $attachName, $module, $oprId, $keepOld = false) {
        switch ($module) {
            case self::MODULE_RESUME:
                $destination = $module;
                break;
            default:
                throw new \RuntimeException('附件模块[' . $module . ']未定义');
        }

        $fileHandler = new FileHandler($file);
        $destination = config('app.file_attach.directory', '') . '/' . $destination;
        try {
            $targetInfo = $fileHandler->move(true, $destination, $keepOld);
        } catch (\Exception $e) {
            Log::error('文件上传失败[' . $e->getMessage() . ']');
            return false;
        }
        $attachId = $targetInfo['fileid'];
        $attachType = self::TYPE_OTHER;
        $filePath = $targetInfo['relativepathname'];
        $fileSize = $targetInfo['filesize'];
        $this->addAttach($oprId, $attachId, $attachName, $attachType, $filePath, $fileSize);
        return $targetInfo;
    }

    /**
     * 获取附件信息
     * @param $attachId
     * @param null $field
     * @return mixed
     */
    public function getAttach($attachId, $field = null) {
        $field = $field ?? 'attachid,attachname,attachtype,filepath,creator';
        $sql = 'SELECT ' . $field . ' from Attach WHERE attachid=?';
        $var = [$attachId];
        return Db::connect()->selectOne($sql, $var);
    }

    /**
     * Notes:批量获取附件信息
     * @param $attachids
     * @param string $field
     * @return array
     */
    public function batchGetAttach($attachids, $field = 'attachid,attachname,attachtype,filepath,creator'){
        $inFlag = substr(str_repeat('?,', count($attachids)), 0, -1);
        $sql = 'SELECT '.$field.' FROM Attach WHERE  attachid IN(' . $inFlag . ')';
        return Db::select($sql,$attachids);
    }

    /**
     * 添加附件
     * @param $oprId
     * @param $attachId
     * @param $attachName
     * @param $attachType
     * @param $filePath
     * @param $fileSize
     * @return bool
     */
    public function addAttach($oprId, $attachId, $attachName, $attachType, $filePath, $fileSize) {
        $sql = 'INSERT INTO Attach(attachid,attachname,attachtype,filepath,creator,createdate,updator,updatedate,status,size) VALUES(?,?,?,?,?,Now(),?,Now(),?,?)';
        $var = [
            $attachId, $attachName, $attachType, $filePath, $oprId, $oprId, '01', $fileSize
        ];
        return Db::insert($sql, $var);
    }

}